Imports System.Text

Public Class MyDataGridView

    Inherits DataGridView

    Public Sub New()
    End Sub

    Protected Overloads Overrides Function ProcessDialogKey(ByVal keyData As Keys) As Boolean

        If keyData = Keys.Enter Then

            MyBase.ProcessTabKey(Keys.Tab)
            Return True
        End If

        Return MyBase.ProcessDialogKey(keyData)

    End Function

    Protected Overloads Overrides Function ProcessDataGridViewKey(ByVal e As KeyEventArgs) As Boolean

        If e.KeyCode = Keys.Enter Then
            MyBase.ProcessTabKey(Keys.Tab)
            Return True
        End If

        Return MyBase.ProcessDataGridViewKey(e)

    End Function
    Protected Overloads Overrides Sub OnRowPostPaint(ByVal e As DataGridViewRowPostPaintEventArgs)
        MyBase.OnRowPostPaint(e)

        ' get the row number in leading zero format, 
        ' where the width of the number = the width of the maximum number 
        Dim RowNumWidth As Integer = Me.RowCount.ToString().Length
        Dim RowNumber As New StringBuilder(RowNumWidth)
        RowNumber.Append(e.RowIndex + 1)
        While RowNumber.Length < RowNumWidth
            RowNumber.Insert(0, " ")
        End While

        ' get the size of the row number string 
        Dim Sz As SizeF = e.Graphics.MeasureString(RowNumber.ToString(), Me.Font)

        ' adjust the width of the column that contains the row header cells 
        If Me.RowHeadersWidth < CInt((Sz.Width + 20)) Then
            Me.RowHeadersWidth = CInt((Sz.Width + 20))
        End If

        ' draw the row number 
        e.Graphics.DrawString(RowNumber.ToString(), Me.Font, SystemBrushes.ControlText, e.RowBounds.Location.X + 15, e.RowBounds.Location.Y + ((e.RowBounds.Height - Sz.Height) / 2))
    End Sub



End Class



